<template>
  <div class="team-salary-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Money /></el-icon>
            <span class="header-title">团队薪资</span>
          </div>
          <div class="header-right">
            <el-button type="success" @click="exportData" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              导出Excel
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="teamSalaryList" 
        style="width: 100%"
        stripe
        :empty-text="'暂无团队薪资记录'"
      >
        <el-table-column label="员工" width="150" align="center">
          <template #default="scope">
            <span>{{ scope.row.userName || `员工${scope.row.userId}` }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="month" label="月份" width="140" align="center">
          <template #default="scope">
            <span class="month-text">{{ scope.row.month }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="baseSalary" label="基本工资" width="140" align="right">
          <template #default="scope">
            <span class="salary-text">¥{{ formatMoney(scope.row.baseSalary) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="bonus" label="奖金" width="140" align="right">
          <template #default="scope">
            <span class="bonus-text">+¥{{ formatMoney(scope.row.bonus || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="deduction" label="扣除" width="140" align="right">
          <template #default="scope">
            <span class="deduction-text">-¥{{ formatMoney(scope.row.deduction || 0) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="实发工资" width="160" align="right">
          <template #default="scope">
            <span class="total-text">¥{{ formatMoney(scope.row.total) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="scope">
            <span class="time-text">{{ formatDate(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="teamSalaryList.length > 0" class="summary-section">
        <el-card class="summary-card" shadow="never">
          <div class="summary-content">
            <div class="summary-item">
              <span class="summary-label">团队人数：</span>
              <span class="summary-value">{{ teamMemberCount }}人</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">团队总薪资：</span>
              <span class="summary-value highlight">¥{{ formatMoney(teamTotalSalary) }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">平均薪资：</span>
              <span class="summary-value highlight">¥{{ formatMoney(avgTeamSalary) }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import request from '../utils/request'
import { ElMessage } from 'element-plus'
import { Money, Download } from '@element-plus/icons-vue'

export default {
  name: 'TeamSalary',
  components: {
    Money,
    Download
  },
  setup() {
    const teamSalaryList = ref([])
    const exportLoading = ref(false)
    
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      return new Date(dateStr).toLocaleString('zh-CN')
    }
    
    const formatMoney = (amount) => {
      if (!amount) return '0.00'
      return Number(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    }
    
    const loadTeamSalary = async () => {
      try {
        // 获取团队薪资（这里简化处理，实际应该根据组织架构查询下属）
        const res = await request.get('/salary/team')
        teamSalaryList.value = res.data || []
      } catch (error) {
        // 如果接口不存在，尝试获取所有薪资记录
        try {
          const res = await request.get('/salary/all')
          teamSalaryList.value = res.data || []
        } catch (err) {
          ElMessage.error('加载团队薪资失败')
        }
      }
    }
    
    const teamMemberCount = computed(() => {
      const userIds = new Set(teamSalaryList.value.map(item => item.userId))
      return userIds.size
    })
    
    const teamTotalSalary = computed(() => {
      return teamSalaryList.value.reduce((sum, item) => {
        return sum + (Number(item.total) || 0)
      }, 0)
    })
    
    const avgTeamSalary = computed(() => {
      if (teamSalaryList.value.length === 0) return 0
      return teamTotalSalary.value / teamSalaryList.value.length
    })
    
    // 导出数据
    const exportData = async () => {
      exportLoading.value = true
      try {
        const token = localStorage.getItem('token')
        const url = '/api/salary/export'
        
        const response = await fetch(url, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        if (!response.ok) {
          throw new Error('导出失败')
        }
        
        const blob = await response.blob()
        const downloadUrl = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = downloadUrl
        link.download = `团队薪资记录_${new Date().toISOString().slice(0, 7)}.xlsx`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(downloadUrl)
        
        ElMessage.success('导出成功')
      } catch (error) {
        ElMessage.error('导出失败：' + (error.message || '未知错误'))
      } finally {
        exportLoading.value = false
      }
    }
    
    onMounted(() => {
      loadTeamSalary()
    })
    
    return {
      teamSalaryList,
      formatDate,
      formatMoney,
      teamMemberCount,
      teamTotalSalary,
      avgTeamSalary,
      exportLoading,
      exportData
    }
  }
}
</script>

<style scoped>
.team-salary-container {
  width: 100%;
  height: 100%;
}

.page-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
  color: #67c23a;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.month-text {
  font-weight: 500;
  color: #333;
}

.salary-text {
  color: #333;
  font-weight: 500;
}

.bonus-text {
  color: #67c23a;
  font-weight: 500;
}

.deduction-text {
  color: #f56c6c;
  font-weight: 500;
}

.total-text {
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
}

.time-text {
  color: #666;
  font-size: 14px;
}

.summary-section {
  margin-top: 24px;
}

.summary-card {
  background: #f5f7fa;
  border: none;
}

.summary-content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 16px 0;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.summary-label {
  font-size: 14px;
  color: #666;
}

.summary-value {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.summary-value.highlight {
  color: #409eff;
  font-size: 24px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 16px 0;
}
</style>

